<template>
  <div>
    <!--面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片视图区域-->
    <el-card class="box-card">
      <!--警告区-->
      <el-row>
        <el-alert
          title="注意：只允许为第三级分类设置相关参数"
          type="warning"
          show-icon
          :closable="false">
        </el-alert>
      </el-row>
      <!--选择商品分类区-->
      <el-row>
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            v-model="selectParamsKeys"
            :options="paramsList"
            :props="{ expandTrigger: 'hover',value:'cat_id',label:'cat_name',children:'children' }"
            @change="handleChange"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>
      <!--tabs页签区-->
      <el-tabs v-model="activeName" @tab-click="handleTabsClick">
        <el-tab-pane label="动态参数" name="many">
          <el-row>
              <el-button type="primary" size="small" :disabled="isBtnDisabled" @click="addParamsDialogVisible=true">添加参数</el-button>
          </el-row>
          <!--动态参数表格-->
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index,scope.row)"
                >
                  {{item}}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditParamsDialog(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParamsById(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-row>
              <el-button type="primary" size="small" :disabled="isBtnDisabled" @click="addParamsDialogVisible=true">添加属性</el-button>
          </el-row>
          <!--静态属性表格-->
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="handleClose(index,scope.row)"
                >
                  {{item}}
                </el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditParamsDialog(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParamsById(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!--添加参数和属性对话框-->
    <el-dialog
      :title="'添加'+titleText"
      :visible.sync="addParamsDialogVisible"
      width="50%"
      @close="addParamsDialogClosed"
    >
      <el-form :rules="addParamsFormRule" ref="addParamsFormRef" :model="addParamsForm" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>
    <!--编辑参数和属性对话框-->
    <el-dialog
      :title="'编辑'+titleText"
      :visible.sync="editParamsDialogVisible"
      width="50%"
      @close="editParamsDialogClosed"
    >
      <el-form :rules="editParamsFormRule" ref="editParamsFormRef" :model="editParamsForm" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: "Params",
    data() {
      return {
        //商品分类参数
        paramsList:[],
        //级联选择框双向绑定的id数组
        selectParamsKeys:[],
        //tabs页签选中页
        activeName:"many",
        //动态参数表格数据
        manyTableData:[],
        //静态属性表格数据
        onlyTableData:[],
        //控制添加参数和属性对话框是否隐藏
        addParamsDialogVisible:false,
        //控制编辑参数和属性对话框是否隐藏
        editParamsDialogVisible:false,
        //添加参数的表单数据对象
        addParamsForm:{
          attr_name:"",
        },
        //编辑参数的表单数据对象
        editParamsForm:{},
        //添加表单的验证规则
        addParamsFormRule:{
          attr_name:[
            {required:true,message:"请输入参数名称", trigger:"blur"}
          ]
        },
        //编辑表单的验证规则
        editParamsFormRule:{
          attr_name:[
            {required:true,message:"请输入参数名称", trigger:"blur"}
          ]
        }
      }
    },
    created() {
      this.getParamsList()
    },
    methods:{
      //获取所有的商品分类列表
      async getParamsList(){
        const result=(await this.$http.get("categories")).data;
        if(result.meta.status!==200) return this.$message.error("请求商品分类失败");
        this.paramsList=result.data;
      },
      //级联选择框选种的选项发生变化
      handleChange(){
        this.getParamsData();
      },
      //tabs页签点击事件
      handleTabsClick(){
        this.getParamsData();
      },
      async getParamsData(){
        //证明选中的不是三级分类
        if(this.selectParamsKeys.length!==3){
          this.selectParamsKeys=[];
          this.manyTableData=[];
          this.onlyTableData=[];
          return
        }
        //根据所选id，分类面板，获取对应的参数
        const result=(await this.$http.get("categories/" +this.paramsId+ "/attributes",
          {params:{sel:this.activeName}})).data;
        if(result.meta.status!==200) return this.$message.error("获取参数失败");
        result.data.forEach(item=>{
          item.attr_vals=item.attr_vals?item.attr_vals.split(" "):[];
          //控制文本框的显示与隐藏
          item.inputVisible=false;
          //文本框中输入的值
          item.inputValue="";
        })
        if (this.activeName==="many"){
          this.manyTableData=result.data;
        }else this.onlyTableData=result.data;
      },
      //添加参数和属性对话框关闭事件
      addParamsDialogClosed(){
        this.$refs.addParamsFormRef.resetFields();
      },
      //点击添加参数和属性
      addParams(){
        this.$refs.addParamsFormRef.validate(async valid=>{
          if(!valid) return;
          const result=(await this.$http.post("categories/" + this.paramsId + "/attributes",
            {attr_name: this.addParamsForm.attr_name, attr_sel: this.activeName})).data;
          if(result.meta.status!==201) return this.$message.error("添加数据失败");
          this.$message.success("添加数据成功")
          this.getParamsData();
          this.addParamsDialogVisible=false;
        })
      },
      //编辑对话框显示与隐藏
      async showEditParamsDialog(attr_id){
        const  result=(await this.$http.get("categories/" + this.paramsId + "/attributes/" + attr_id,
          {params: {attr_sel: this.activeName}})).data;
        if(result.meta.status!==200) return this.$message.error("请求参数失败");
        this.editParamsForm=result.data;
        this.editParamsDialogVisible=true;
      },
      //添加参数和属性对话框关闭事件
      editParamsDialogClosed(){
        this.$refs.editParamsFormRef.resetFields();
      },
      //点击编辑参数和属性
      editParams(){
        this.$refs.editParamsFormRef.validate(async valid=>{
          if(!valid) return;
          const result=(await this.$http.put("categories/" + this.paramsId + "/attributes/"+this.editParamsForm.attr_id,
            {attr_name: this.editParamsForm.attr_name, attr_sel: this.activeName})).data;
          if(result.meta.status!==200) return this.$message.error("编辑数据失败");
          this.$message.success("编辑数据成功")
          this.getParamsData();
          this.editParamsDialogVisible=false;
        })
      },
      //删除参数和属性
      removeParamsById(attr_id){
        //用户确认删除，返回字符串confirm，取消删除，返回字符串cancel
        this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            const result=(await this.$http.delete("categories/" + this.paramsId+"/attributes/"+attr_id)).data;
            if(result.meta.status!==200) return this.$message.error("删除失败");
            this.$message.success('删除成功!');
            this.getParamsData();
          })
          .catch(() => {
            this.$message.info('已取消删除');
          });
      },
      //文本框失去焦点或按下了Enter键
      async handleInputConfirm(row){
        if(row.inputValue.trim().length===0) {
          row.inputValue = "";
          row.inputVisible=false;
          return;
        }
        //如果没有return,则证明有输入的内容，需要做后续处理
        row.attr_vals.push(row.inputValue.trim());
        row.inputValue="";
        row.inputVisible=false;
        this.saveAttrVals(row);
      },
      //点击按钮展示文本输入框
      showInput(row){
        row.inputVisible=true;
        //$nextTick,当页面上元素被重新渲染之后，才会执行回调函数中的代码
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
      //点击删除标签
      async handleClose(index,row){
        row.attr_vals.splice(index,1);
        this.saveAttrVals(row);
      },
       async saveAttrVals(row){
         //保存进数据库
         const result=(await this.$http.put("categories/" + this.paramsId + "/attributes/" + row.attr_id,
           {attr_name:row.attr_name,attr_sel:row.attr_sel,attr_vals:row.attr_vals.join(" ")})).data;
         if(result.meta.status!==200) return this.$message.error("修改失败");
         this.$message.success("修改成功");
      }
    },
    computed:{
      //如果按钮被禁用则返回true，否则返回false
      isBtnDisabled(){
        if(this.selectParamsKeys.length!==3) return true;
        return false;
      },
      //当前选中的三级分类的id
      paramsId(){
        if(this.selectParamsKeys.length===3){
          return this.selectParamsKeys[2];
        }
        return null;
      },
      //动态计算添加文本框标题的文本
      titleText(){
        if(this.activeName==="many"){
          return "动态参数"
        }else return "静态属性"
      }
    }
  }
</script>

<style scoped lang="less">
  .el-tag{
    margin: 10px;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: center;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
</style>
